from pathlib import Path

from PySide6.QtWidgets import QScrollArea, QVBoxLayout, QWidget, QSizePolicy
from PySide6.QtCore import Signal, Slot

from ledger2others import ledger_convert, ledger_one_year
from api import api_ui

class LedgerUiScroll(QScrollArea):
    rel_tip_signal = Signal(str, str)
    show_msg_signal = Signal(dict)
    send_to_subthread_signal = Signal(bool)
    send_ledger_signal = Signal(list)
    log_signal = Signal(str, str)

    def __init__(self, group_box_style: str):
        super().__init__()
        self.GROUP_BOX_STYLE = group_box_style
        self.setStyleSheet("QScrollArea { border: none; }")        # 设置样式表，消除白线
        self.setWidgetResizable(True)
        self.setup_ui()
    
    def setup_ui(self):
        # 选择结算支付台账的路径
        ledger_layout, ledger_label, self.ledger_edit, ledger_button = api_ui.file_path_ui('结算支付台账')
        ledger_button.clicked.connect(lambda: api_ui.select_folder(self.ledger_edit))
        # 文件转换box
        convert_group_box = ledger_convert.LedgerConvertUi(self.GROUP_BOX_STYLE)
        convert_group_box.rel_tip_signal.connect(self.rel_tip_signal)
        convert_group_box.show_msg_signal.connect(self.show_msg_signal)
        convert_group_box.send_to_subthread_signal.connect(self.send_to_subthread_signal)
        convert_group_box.request_ledger_signal.connect(self.send_ledger_path)
        convert_group_box.log_signal.connect(self.log_signal)
        self.send_ledger_signal.connect(convert_group_box.receive_ledger_path)
        
        # 一年期box
        one_year_group_box = ledger_one_year.LedgerOneYear(self.GROUP_BOX_STYLE)
        one_year_group_box.rel_tip_signal.connect(self.rel_tip_signal)
        one_year_group_box.show_msg_signal.connect(self.show_msg_signal)
        one_year_group_box.request_ledger_signal.connect(self.send_ledger_path)
        one_year_group_box.log_signal.connect(self.log_signal)
        self.send_ledger_signal.connect(one_year_group_box.receive_ledger_path)

        main_widget = QWidget()
        # 需要添加（确保内容可以展开）
        main_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)
        main_layout.addLayout(ledger_layout)
        main_layout.addWidget(convert_group_box)
        main_layout.addWidget(one_year_group_box)
        # self.setLayout(main_layout)
        self.setWidget(main_widget)


    @Slot()
    def send_ledger_path(self):
        ledger_path =  self.ledger_edit.text().split(', ')
        if ledger_path == '':
            self.show_msg_signal.emit({'message': '请选择结算支付台账的路径'})
            self.send_ledger_signal.emit(None)
            return
        self.send_ledger_signal.emit(ledger_path)

    @Slot(bool)
    def receive_decision(self, choice):
        """槽函数，用于接收用户选择，并发送给子线程"""
        self.send_to_subthread_signal.emit(choice)